from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from . import models
from . import serializer
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response


class BannerView(GenericViewSet, ListModelMixin):
    # 每页轮播图都有固定的显示个数
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by("orders")[:settings.BANNER_COUNTER]
    serializer_class = serializer.BannerModelSerializer

    def list(self, request, *args, **kwargs):
        # 去缓存中拿数据
        banner_list = cache.get("banner_list")
        if not banner_list:
            # 缓存中没有数据，去数据库中拿
            response = super().list(request, *args, **kwargs)
            # 过期时间为 1 天
            cache.set("banner_list", response.data, 60*60*24)
            return response

        return Response(data=banner_list)